import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import type { IResponse } from '@nbase/shared';
import { RESPONSE_CODE, RESPONSE_MESSAGE } from '@nbase/shared';

/**
 * 统一响应格式拦截器
 * 
 * 自动将 Controller 返回的数据包装为统一格式：
 * { code: 0, data: ..., message: '操作成功', timestamp: '...' }
 * 
 * 适用于所有成功响应（异常由 HttpExceptionFilter 处理）
 */
@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, IResponse<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler
  ): Observable<IResponse<T>> {
    return next.handle().pipe(
      map((data) => ({
        code: RESPONSE_CODE.SUCCESS,
        data: data ?? null,  // 确保 data 字段始终存在
        message: RESPONSE_MESSAGE[RESPONSE_CODE.SUCCESS],
        timestamp: new Date().toISOString(),
      }))
    );
  }
}

